package com.simen.android.websocket;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class MainActivity extends AppCompatActivity {
    
    private static final String TAG = "MainActivity";
    
    private static final char lf = 10; // 换行
    private static final char nl = 0; // 消息结尾的标记，一定要
    
    TextView message;
    
    OkHttpClient okHttpClient;
    
    WebSocket webSocket;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        message = findViewById(R.id.message);
        
        findViewById(R.id.connect).setOnClickListener(v -> {
            Request request = new Request.Builder()
                    //.url("ws://10.24.240.91:8080/gs-guide-websocket/websocket")
                    .url("ws://10.24.248.43:5566/web-im/web/channel")
                    //.url("ws://10.24.240.91:8080/ws/websocket")
                    //.url("http://10.24.240.91:8080/gs-guide-websocket/info?t="+System.currentTimeMillis())
                    //.url("ws://echo.websocket.org")
                    .build();
            
            webSocket = okHttpClient.newWebSocket(request, new MyWebSocketListener());
        });
        
        findViewById(R.id.other).setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, OtherActivity.class));
        });
        
        findViewById(R.id.disConnect).setOnClickListener(v -> {
            if (webSocket != null) {
                //Code must be in range [1000,5000):
                webSocket.close(1000, "bye!");
                //webSocket.cancel();
                webSocket = null;
            }
        });
        
        findViewById(R.id.subscribe).setOnClickListener(v -> {
            if (webSocket != null) {
                StringBuilder sb = new StringBuilder();
                
                sb.append("SUBSCRIBE").append(lf); // 请求的命令策略
                sb.append("id:sub-9").append(lf);
                sb.append("destination:/topic/greetings").append(lf).append(lf).append(nl);
                
                webSocket.send(sb.toString());
            } else {
                Log.e(TAG, "webSocket is null");
            }
        });
        
        Button button = findViewById(R.id.hello);
        button.setOnClickListener(v -> {
            String msgTemplate = "{\"name\":\"%1$s\"}";
            String msg = String.format(msgTemplate, "android");
            
            if (webSocket != null) {
                StringBuilder sb = new StringBuilder();
                
                sb.append("SEND").append(lf); // 请求的命令策略
                sb.append("destination:/app/hello").append(lf); // 请求的资源
                sb.append("content-length:" + msg.length()).append(lf).append(lf); // 消息体的长度
                sb.append(msg).append(nl); // 消息体
                
                webSocket.send(sb.toString());
            } else {
                Log.e(TAG, "webSocket is null");
            }
        });
        
        okHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(
                        new HttpLoggingInterceptor()
                                .setLevel(HttpLoggingInterceptor.Level.BODY)
                )
                .readTimeout(15 * 1000, TimeUnit.SECONDS)
                .writeTimeout(15 * 1000, TimeUnit.SECONDS)
                .connectTimeout(15 * 1000, TimeUnit.SECONDS)
                .build();
    }
    
    private static class MyWebSocketListener extends WebSocketListener {
        
        private static final String TAG = "MyWebSocketListener";
        
        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            super.onOpen(webSocket, response);
            Log.d(TAG, "onOpen: ");
        }
        
        @Override
        public void onMessage(WebSocket webSocket, String text) {
            super.onMessage(webSocket, text);
            Log.d(TAG, "onMessage1: " + text);
        }
        
        @Override
        public void onMessage(WebSocket webSocket, ByteString bytes) {
            super.onMessage(webSocket, bytes);
            Log.d(TAG, "onMessage2: " + bytes.utf8());
        }
        
        @Override
        public void onClosing(WebSocket webSocket, int code, String reason) {
            super.onClosing(webSocket, code, reason);
            Log.d(TAG, "onClosing: ");
        }
        
        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            super.onClosed(webSocket, code, reason);
            Log.d(TAG, "onClosed: ");
        }
        
        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
            super.onFailure(webSocket, t, response);
            Log.e(TAG, "onFailure: ", t);
        }
    }
}
